<?php
/**
 * @author GhostWei
 * @date Sep 9, 2012
 */
class controller_www_account_avatar extends front_controller_ajax {	
	
	public function init() {
		/**
		 * 解决 SWFUpload SESSION  丢失问题
		 */
		if(1 && $sid = $this->_post('sid')) {
			session_write_close();
			session_id($sid);
			session_start();
		}
		if(!parent::init() || $this->login(array('ajax' => true))) {
			return ;
		}
	}
	
	public function action_update() {
		try {
			if($this->_post('submit') == 'update') {
				if(!($hash = $this->_post('hash'))) {
					$this->_error('请选择一个头像更新');
				}
				$row = $this->user;
				try {
					system_db::getAdapter()->beginTransaction();					
					$row->setAvatar($hash);
					$row->update();
					system_db::getAdapter()->commit();
					$this->_data->hash = $hash;
					$this->_output();
				} catch (Exception $e) {
					system_db::getAdapter()->rollBack();
					throw $e;
				}
			} else {
				$filename = resource_api_avatar::getTempFileName();
				$resRow = resource_api_avatar::create(array(
							'tmp_name' => $filename,
							'size' => filesize($filename)
						), (array) $this->getRequest()->getPost('crop'));
				$row = $this->user;
				try {
					system_db::getAdapter()->beginTransaction();
					$resRow->save();
					
					$avatarConcept = new community_member_avatar_concept();
					$avatarRow = $avatarConcept->create();
					$avatarRow->setPassportId($row->getPassportId());
					$avatarRow->setHash($resRow->getHash());
					$avatarRow->setCreationip($this->getRequest()->getClientIp(true));
					$avatarRow->save();
					
					$row->setAvatar($resRow->getHash());
					$row->update();
					system_db::getAdapter()->commit();
					$this->_data->hash = $resRow->getHash();
					$this->_output();
				} catch (Exception $e) {
					system_db::getAdapter()->rollBack();
					throw $e;
				}
			}
		} catch (Exception $e) {
			$this->_error($e->getMessage());
		}
	}
	
	public function action_upload() {
		try {
			$thumb = resource_api_avatar::createTemp($_FILES['file']);
			$format = $thumb->getCurrentDimensions();
			$this->_data->file = array(
					'width' => $format['width'],
					'height' => $format['height'],
					'size' => filesize($thumb->getFileName())
			);
			$this->_output();
		} catch (Exception $e) {
			$this->_error($e->getMessage());
		}
	}
	
	public function action_preview() {
		$filename = resource_api_avatar::getTempFileName();
		if(!file_exists($filename)) {
			$this->_redirector(resource_config_avatar::noMedia());
		}
		$formatInfo = getimagesize($filename);
		if(!($formatInfo = getimagesize($filename))) {
			$this->_redirector(resource_config_avatar::noMedia());
		}
		$mime = $formatInfo['mime'];
		$data = file_get_contents($filename);
		header("Content-type: $mime");
		echo $data;
	}
	
	
}
